package cn.bluedot.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 验证码类
 * 
 * @author 任志江
 *
 */
public class VerifyCode {

	/**
	 * 将图片缓冲区的内容以JPEG格式写入到输出流
	 * @param bi : 图片缓冲区
	 * @param os : 输出流
	 * @throws IOException : 如果写入过程中发生错误，抛出IOException
	 * @throws IllegalArgumentException :如果参数错误
	 */
	public static void output(BufferedImage bi, OutputStream os) throws IOException
	{
		if(bi == null || os == null)
			throw new IllegalArgumentException("传入参数为空");
		ImageIO.write(bi, "JPEG", os);
	}
	/**
	 * 生成一个验证码图片的图片缓冲区
	 * @return BufferedImage:验证码图片的缓冲
	 */
	public BufferedImage getImage()
	{
		//初始化text
		text = "";
		//生成图片缓冲区
		BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		
		Graphics2D g = (Graphics2D)bi.getGraphics();
		//设置背景色
		g.setBackground(bgC);
		//绘制填充边框
		g.fillRect(0, 0, w, h);
		//绘制文本
		for(int i = 0;i < 4;i++)
		{
			int start = i * w / 4;
			//生成随机字体
			g.setFont(getRandomFont());
			//生成随机颜色
			g.setColor(getRandomColor());
			//生成随机字符
			String str = getRandomStr();
			//绘制
			g.drawString(str, start, h-5);
			//加入text
			text += str;
		}
		//绘制干扰线
		drawLine(bi);
		return bi;
	}
	
	/**
	 * 返回最近的到图片验证码的字符串
	 * @return String:图片缓冲中的文本内容
	 */
	public String getText()
	{
		return text;
	}
	
	//生成随机文本 例如："a"
	private String getRandomStr()
	{
		int index = r.nextInt(codes.length());
		return codes.substring(index, index+1);
	}
	//生成随机字体
	private Font getRandomFont()
	{
		int leng = fontName.length;
		int name_index = r.nextInt(leng);
		int style = r.nextInt(4);//0普通字体 1粗体 2斜体 3粗斜
		int size = 35 + r.nextInt(5);
		return new Font(fontName[name_index], style, size);
	}
	//生成随机颜色
	private Color getRandomColor()
	{
		int r = 30 + this.r.nextInt(156);
		int g = 50 + this.r.nextInt(156);
		int b = 50 + this.r.nextInt(156);
		return new Color(r, g, b);
	}
	//绘制干扰线
	private void drawLine(BufferedImage bi)
	{
		Graphics2D g = (Graphics2D)bi.getGraphics();
		int x1,y1,x2,y2;
		for(int i = 0;i < 3;i++)
		{
			//获取随机颜色
			Color c = getRandomColor();
			g.setColor(c);
			x1 = r.nextInt(w);
			x2 = r.nextInt(w);
			y1 = r.nextInt(h);
			y2 = r.nextInt(h);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	//验证码的宽度
	private int w = 75;
	//验证码的高度
	private int h = 35;
	//随机数生成类
	private Random r = new Random();
	//字体
	private String[] fontName = {"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"};
	//可选字符
	private String codes = "23456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	//背景色
	private Color bgC = new Color(255, 255, 255);
	//验证码是的文本
	private String text = null;
}







